# -*- coding: utf-8 -*-
# @Time        :2025/3/5 16:04
# @Author      :文刀水寿
# @File        : 18_爬虫_解析_xpath的基本使用.py
"""
 @Description :
"""
# 主流的三种解析方式
# xpath
# JsonPath
# BeautifulSoup
# ---
# etree.parse()   解析本地文件
# html_tree = etree.parse("xx.gtml")
#
# etree.HTML()    服务器响应文件
# html_tree = etree.HTML(response.read().decode('utf8'))
#
# html_tree.xpath(xpath路径)

from lxml import etree

#   xpath 基本语法
tree = etree.parse('xpath的基本使用.html')
# # 1.路径查询
# //: 查找所有子孙节点，不考虑层级关系
# /: 找直接子节点
# 查找ul下面的li
li_list = tree.xpath('//ul/li')
# 查找所有有id的属性的li标签
li_list = tree.xpath('//ul/li[@id]/text()')

# # 2.谓词查询
# //div[@id]
# /div[@id='maincontent']
# 找到id为l1的标签
li_list = tree.xpath('//ul/li[@id="l1"]/text()')

# #3. 属性查询
# //@class
# 查找到id为l1的标记的class的属性值
li_list = tree.xpath('//ul/li[@id="l1"]/@class')

# # 4.模糊查询
# //div[contains(@id, 'he')]
# //div[starts-with(@id, "he")]
# 查找id中包含l1的标签
li_list = tree.xpath('//ul/li[contains(@id, "l1")]/text()')
# 查询id的值以l开头的li标签
li_list = tree.xpath('//ul/li[starts-with(@id, "l")]/text()')

# # 5.内容查询
# //div/h1/text()
# /text()

# # 6.运算逻辑
# //div[@id="head" and @class="s_down"]
# //title | price
# 查询id为l1和c1的
li_list = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')
li_list = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')

print(li_list)
print(len(li_list))
